var domainRegEx = /^([^:]+:\/\/)([^\/]+)/;
function onBeforeRequest(details)
{
	var domain = details.url.match(domainRegEx)[2];
	if(KnownDomains.indexOf(domain) != -1 && 
		domain != Options.Domain.Current)
		return {redirectUrl:details.url.replace(domainRegEx, "$1" + 
			Options.Domain.Current)};
}

function onTabsUpdated(tabId, changeInfo, tab)
{
	var domain_match = (changeInfo.url || "").match(domainRegEx);
	var domain;
	if(domain_match && (domain = domain_match[2]) && 
		KnownDomains.indexOf(domain) != -1 && 
		domain != Options.Domain.Current)
		chrome.tabs.update(tabId, {url: changeInfo.url.replace(
			domainRegEx, "$1" + Options.Domain.Current)});
}

Options.Domain.onChanged = (function(details)
{
	if(Options.Domain.Force)
	{
		chrome.webRequest && chrome.webRequest.onBeforeRequest.addListener(
			onBeforeRequest, {urls: DomainMatchPatterns}, ["blocking"]);
		!chrome.webRequest && chrome.tabs.onUpdated.addListener(
			onTabsUpdated);
	}
	else
	{
		chrome.webRequest && chrome.webRequest.onBeforeRequest.
			removeListener(onBeforeRequest);
		!chrome.webRequest && chrome.tabs.onUpdated.removeListener(
			onTabsUpdated);
	}
});

if(Options.Domain.AutoDetect)
{
	//TODO: Check for domain
}

Options.Domain.Force && Options.Domain.onChanged(
	{name: "Force", newValue: true});

